package com.changfeng.controller;

import com.changfeng.bean.dto.vo.CategoryListVO;
import com.changfeng.exception.ChangFengException;
import com.changfeng.exception.ChangFengExceptionEnum;
import com.changfeng.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/findAll")
    public List<CategoryListVO> findAll(){
        return categoryService.findAll();
    }


    @GetMapping("/findByBrandId")
    public List<CategoryListVO> findByBrandId(Integer brandId) {

        if (brandId == null) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }

        return categoryService.findByBrandId(brandId);
    }

    @GetMapping("/findByCategoryId")
    public CategoryListVO findByCategoryId(Integer categoryId) {
        if (categoryId == null) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }
        CategoryListVO byCategoryId = categoryService.findByCategoryId(categoryId);
        if (byCategoryId == null) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }
        return byCategoryId;
    }

    @PostMapping("/saveCategory")
    public void saveCategory(@RequestBody CategoryListVO vo) {
        if (vo == null) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }
        if (vo.getCategoryName() == null || vo.getCategoryName().equals("")) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }
        if (vo.getCategoryId() == null) {
            categoryService.saveCategory(vo);
        } else {
            categoryService.updateCategory(vo);
        }
    }

    @GetMapping("/deleteCategory")
    public void deleteCategory(Integer categoryId) {
        if (categoryId == null) {
            throw new ChangFengException(ChangFengExceptionEnum.PARAM_EXCEPTION);
        }
        categoryService.deleteCategory(categoryId);
    }


}
